package cn.stylefeng.guns.modular.appapi;


import cn.stylefeng.guns.modular.fileTag.service.FileTagService;
import cn.stylefeng.guns.modular.leaveapproval.service.LeaveApprovalService;
import cn.stylefeng.guns.modular.leaveinfo.service.LeaveInfoService;
import cn.stylefeng.guns.modular.studentmanage.model.LeaveUserResult;
import cn.stylefeng.guns.modular.studentmanage.service.StuManageService;
import cn.stylefeng.guns.sys.modular.system.entity.FileTagPO;
import cn.stylefeng.guns.sys.modular.system.entity.LeaveApprovalPO;
import cn.stylefeng.guns.sys.modular.system.entity.LeaveInfoPO;
import cn.stylefeng.guns.sys.modular.system.entity.LeaveUserPO;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/leaveAppApi")
public class LeaveAppApiController {
    @Autowired
    private StuManageService stuManageService;

    @Autowired
    private LeaveInfoService leaveInfoService;

    @Autowired
    private LeaveApprovalService leaveApprovalService;

    @Autowired
    private FileTagService fileTagService;

    /**
     * 登录接口
     *
     * @Date 2019-02-18
     */
    @CrossOrigin(origins = "*")
    @RequestMapping("/appLogin/{leaveUserNum}/{leaveUserPwd}")
    @ResponseBody
    public ResponseData appLogin(@PathVariable String leaveUserNum, @PathVariable String leaveUserPwd) {
        ResponseData responseData = new ResponseData();
        if (org.apache.commons.lang3.StringUtils.isEmpty(leaveUserNum) || org.apache.commons.lang3.StringUtils.isEmpty(leaveUserPwd)) {
            responseData.setCode(500);
            responseData.setMessage("用户名或密码为空！！！");
        } else {
            LeaveUserPO leaveUserPO = stuManageService.getOne(new QueryWrapper<LeaveUserPO>().eq("leave_user_num", leaveUserNum));
            if (!Objects.isNull(leaveUserPO) && leaveUserPO.getLeaveUserPwd().equals(leaveUserPwd)) {
                responseData.setCode(200);
                responseData.setMessage("登录成功！！！");
                responseData.setData(leaveUserPO);
            } else {
                responseData.setCode(500);
                responseData.setMessage("用户不存在/密码错误！！！");
            }
        }
        return responseData;
    }

    /**
     * 请假请求
     * 如果是存档请将状态置为5，如果为则默认为待审批即状态为0
     */
    @CrossOrigin(origins = "*")
    @PostMapping("/apply")
    @ResponseBody
    public ResponseData apply(LeaveInfoPO leaveInfoPO) {
        //检测是否存在已审批状态得请假
        List<LeaveInfoPO> leaveInfoPOS = leaveInfoService.list(new QueryWrapper<LeaveInfoPO>()
                .eq("leave_user_num", leaveInfoPO.getLeaveUserNum()).
                        and(wrapper -> wrapper.eq("leave_info_status", 0)
                                .or().eq("leave_info_status", 1)));
        if (leaveInfoPOS.size() != 0) {
            return ResponseData.success(500, "新增失败，存在待审批或已审批且未销假的记录", null);
        }
        LeaveUserPO leaveUserPO = stuManageService.getOne(new QueryWrapper<LeaveUserPO>().eq("leave_user_num", leaveInfoPO.getLeaveUserNum()));
        leaveInfoPO.setStairApprovalId(leaveUserPO.getStairApprovalId());
        leaveInfoPO.setFoxbaseApprovalId(leaveUserPO.getFoxbaseApprovalId());
        leaveInfoPO.setTertiaryApprovalId(leaveUserPO.getTertiaryApprovalId());
        //插入请假表
        Long leaveInfoId = leaveInfoService.saveUser(leaveInfoPO);
        if (1 == leaveInfoId.longValue()) {
            //初始化流程
            List<String> logs = new ArrayList<>(3);
            logs.add("申请中/1");
            logs.add("辅导员收到申请/2");
            logs.add("辅导员审核中/3");
            boolean b = leaveInfoService.writeHistory(logs, null, leaveInfoPO.getLeaveInfoId());
            if (b) {
                return ResponseData.success(200, "新增成功", null);
            }
        }
        return ResponseData.success(500, "新增失败", null);
    }


    /**
     * 根据ID获取请假详情
     *
     * @Date 2019-02-18
     */
    @CrossOrigin(origins = "*")
    @RequestMapping("/getLeaveInfoById/{leaveInfoId}")
    @ResponseBody
    public ResponseData getLeaveInfoById(@PathVariable Long leaveInfoId) {
        ResponseData responseData = new ResponseData();
        if (!(null == leaveInfoId)) {
            LeaveInfoPO leaveInfoPO = leaveInfoService.getById(leaveInfoId);
            responseData.setCode(200);
            responseData.setData(leaveInfoPO);
            responseData.setMessage("查询成功");
        } else {
            responseData.setCode(500);
            responseData.setData(null);
            responseData.setMessage("ID未被标识");
        }
        return responseData;
    }

    /**
     * 根据ID删除请假详情
     *
     * @Date 2019-02-18
     */
    @CrossOrigin(origins = "*")
    @RequestMapping("/delLeaveInfoById/{leaveInfoId}")
    @ResponseBody
    public ResponseData delLeaveInfoById(@PathVariable Long leaveInfoId) {
        ResponseData responseData = new ResponseData();
        if (!(null == leaveInfoId)) {
            boolean b = leaveInfoService.removeById(leaveInfoId);
            if (b) {
                responseData.setCode(200);
                responseData.setMessage("删除成功");
            }
        } else {
            responseData.setCode(500);
            responseData.setMessage("ID未被标识");
        }
        return responseData;
    }

    /**
     * 存档请求
     * 如果是存档请将状态置为5，如果为则默认为待审批即状态为0
     */
    @CrossOrigin(origins = "*")
    @PostMapping("/keepFile")
    @ResponseBody
    public ResponseData keepFile(LeaveInfoPO leaveInfoPO) {
        LeaveUserPO leaveUserPO = stuManageService.getOne(new QueryWrapper<LeaveUserPO>().
                eq("leave_user_num", leaveInfoPO.getLeaveUserNum()));
        leaveInfoPO.setStairApprovalId(leaveUserPO.getStairApprovalId());
        leaveInfoPO.setFoxbaseApprovalId(leaveUserPO.getFoxbaseApprovalId());
        leaveInfoPO.setTertiaryApprovalId(leaveUserPO.getTertiaryApprovalId());
        boolean b = leaveInfoService.save(leaveInfoPO);
        if (b) {
            return ResponseData.success(200, "存档成功", null);
        }
        return ResponseData.success(500, "存档失败", null);
    }

    /**
     * 历史请求
     * 如果是存档请将状态置为5，如果为则默认为待审批即状态为0
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/getHistory/{leaveUserNum}")
    @ResponseBody
    public ResponseData getHistory(@PathVariable String leaveUserNum) {
        List<LeaveInfoPO> leaveInfoPOS = leaveInfoService.list(new QueryWrapper<LeaveInfoPO>().eq("leave_user_num", leaveUserNum));
        if (!CollectionUtils.isEmpty(leaveInfoPOS)) {
            return ResponseData.success(200, "查询成功", leaveInfoPOS);
        }
        return ResponseData.success(500, "暂无数据", null);
    }

    /**
     * 待审批请求（0）、已通过（1）、已拒绝（4）
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/getStatusByType/{leaveUserNum}/{type}")
    @ResponseBody
    public ResponseData getStatusByType(@PathVariable String leaveUserNum, @PathVariable Integer type) {
        List<LeaveInfoPO> leaveInfoPOS = leaveInfoService.list(new QueryWrapper<LeaveInfoPO>()
                .eq("leave_user_num", leaveUserNum).and(wrapper -> wrapper.eq("leave_info_status", type)));
        if (!CollectionUtils.isEmpty(leaveInfoPOS)) {
            return ResponseData.success(200, "查询成功", leaveInfoPOS);
        }
        return ResponseData.success(500, "暂无数据", null);
    }

    /**
     * 根据学生学号获取最新请假情况，然后根据请假记录主键获取最新的审批就记录
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/getNowFlowByUserNum/{leaveUserNum}")
    @ResponseBody
    public ResponseData getFurrentFlow(@PathVariable String leaveUserNum) {
        List<LeaveInfoPO> leaveInfoPOS = leaveInfoService.list(new QueryWrapper<LeaveInfoPO>()
                .eq("leave_user_num", leaveUserNum)
                .orderByDesc("leave_info_id"));
        if (!CollectionUtils.isEmpty(leaveInfoPOS)) {
            LeaveInfoPO leaveInfoPO = leaveInfoPOS.get(0);
            List<LeaveApprovalPO> leaveApprovalPOS = leaveApprovalService.list(new QueryWrapper<LeaveApprovalPO>().eq("leave_info_id", leaveInfoPO.getLeaveInfoId()).orderByDesc("leave_approval_tex"));
            return ResponseData.success(200, "查询成功", leaveApprovalPOS);
        }
        return ResponseData.success(500, "暂无数据", null);
    }

    /**
     * 根据请假ID主键审批流程
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/getFurrentFlow/{leaveInfoId}")
    @ResponseBody
    public ResponseData getFurrentFlow(@PathVariable Long leaveInfoId) {
        List<LeaveApprovalPO> leaveInfoPOS = leaveApprovalService.list(new QueryWrapper<LeaveApprovalPO>().eq("leave_info_id", leaveInfoId).orderByDesc("leave_approval_tex"));
        if (!CollectionUtils.isEmpty(leaveInfoPOS)) {
            return ResponseData.success(200, "查询成功", leaveInfoPOS);
        }
        return ResponseData.success(500, "暂无数据", null);
    }

    /**
     * 修改密码
     */
    @CrossOrigin(origins = "*")
    @PutMapping("/modifyMi/{leaveUserNum}/{pwd}")
    @ResponseBody
    public ResponseData modifyMi(@PathVariable String leaveUserNum, @PathVariable String pwd) {
        LeaveUserPO leaveUserPO = stuManageService.getOne(new QueryWrapper<LeaveUserPO>().eq("leave_user_num", leaveUserNum));
        leaveUserPO.setLeaveUserPwd(pwd);
        boolean b = stuManageService.update(leaveUserPO, new QueryWrapper<LeaveUserPO>().eq("leave_user_id", leaveUserPO.getLeaveUserId()));
        if (b) {
            return ResponseData.success(200, "密码重置成功", null);
        }
        return ResponseData.success(500, "密码重置失败", null);
    }

    /**
     * 个人信息
     */
    @CrossOrigin(origins = "*")
    @GetMapping("/getUserById/{leaveUserNum}")
    @ResponseBody
    public ResponseData getUserById(@PathVariable String leaveUserNum) {
        LeaveUserPO leaveUserPO = stuManageService.getOne(new QueryWrapper<LeaveUserPO>().eq("leave_user_num", leaveUserNum));
        LeaveUserResult leaveUserResult = new LeaveUserResult();
        BeanUtils.copyProperties(leaveUserPO, leaveUserResult);
        FileTagPO byId = fileTagService.getById(leaveUserPO.getClbumId());
        leaveUserResult.setClbumName(byId.getTagName());
        if (!Objects.isNull(leaveUserPO)) {
            return ResponseData.success(200, "查询成功", leaveUserResult);
        }
        return ResponseData.success(500, "暂无数据", null);
    }

    /**
     * 编辑资料
     */
    @CrossOrigin(origins = "*")
    @PutMapping("/editingMaterials/{leaveUserNum}")
    @ResponseBody
    public ResponseData ditingMaterials(@PathVariable String leaveUserNum, LeaveUserPO leaveUserPO) {
        LeaveUserPO leaveUserPO2 = stuManageService.getOne(new QueryWrapper<LeaveUserPO>().eq("leave_user_num", leaveUserNum));
        if (!StringUtils.isEmpty(leaveUserPO.getLeaveUserNickName())) {
            leaveUserPO2.setLeaveUserNickName(leaveUserPO.getLeaveUserNickName());
        }
        if (!StringUtils.isEmpty(leaveUserPO.getLeaveUserAddr())) {
            leaveUserPO2.setLeaveUserAddr(leaveUserPO.getLeaveUserAddr());
        }
        boolean b = stuManageService.update(leaveUserPO2, new QueryWrapper<LeaveUserPO>().eq("leave_user_id", leaveUserPO2.getLeaveUserId()));
        if (b) {
            return ResponseData.success(200, "资料编辑成功", null);
        }
        return ResponseData.success(500, "资料编辑失败", null);
    }
}


